package com.wbao.dianniu.http;

import java.io.IOException;
import java.io.Serializable;

import org.apache.http.Header;
import org.apache.http.ParseException;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;

import com.alibaba.mobileim.channel.IMChannel;
import com.alibaba.wxlib.util.SysUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.wbao.dianniu.customView.LoadingDialog;
import com.wbao.dianniu.ui.LoginActivity;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.Notification;

public class HttpUtil implements Serializable{
	/**
	 * 系列化
	 */
	private static final long serialVersionUID = 3479064155440582563L;
	//server ip url
	private  String url = "http://api.dianniuapp.com/";
	// test server url
	private String test_url ="http://118.178.189.156:8080/dianniu/batch/json";
	private  String contentType = "application/json";
	private Dialog pDialog;
	
	
	public interface MyResponse {
		void responseSucess(Object obj);
		void responseFailure(String msg);
	}
	
	public void req(Context context, StringEntity entity, MyResponse response) {
		req(context, entity, false, response);
	}
	
	public  void req(Context context, StringEntity entity, boolean isShowWaitting, MyResponse resp) {
		AsyncHttpClient client = new AsyncHttpClient();
		client.setTimeout(10000);// 设置链接超时，如果不设置，默认为10s
		try {
			System.out.println("请求内容："+EntityUtils.toString(entity, "UTF-8"));
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		IMChannel.DEBUG = Boolean.valueOf(SysUtil.isDebug());
		if(IMChannel.DEBUG){
			url = test_url;
		}
		if (isShowWaitting) {
			pDialog = LoadingDialog.createLoadingDialog(context, "正在加载中..."); 
			pDialog.show();
		}
		client.post(context, url, entity, contentType, new MyHttpResponseHandler(context, resp, isShowWaitting));
	}
	
	public  class MyHttpResponseHandler extends JsonHttpResponseHandler{
		private boolean isShowing;
		private MyResponse resp;
		private Context mContext;
		public MyHttpResponseHandler(Context context,MyResponse resp,boolean isShowing) {
			mContext = context;
			this.isShowing = isShowing;
			this.resp = resp;
		}
		
		@Override
		public void onFailure(int statusCode, Header[] headers,String responseString, Throwable throwable) {
			if(isShowing){
				if(null != pDialog && pDialog.isShowing()){
					pDialog.dismiss();
				}
			}
			Notification.toast(mContext, "连接失败，请检查网络!");
			resp.responseFailure("连接失败，请检查网络!");
		}
		
		@Override
		public void onFailure(int statusCode, Header[] headers,Throwable throwable, JSONObject errorResponse) {
			if(null != throwable && null != throwable.getMessage()){
				if(isShowing){
					if(null != pDialog && pDialog.isShowing()){
						pDialog.dismiss();
					}
				}
				Notification.toast(mContext, "连接失败，请检查网络!");
				resp.responseFailure("连接失败，请检查网络!");
			}
			
		}

		@Override
		public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
			if(isShowing){
				if(null != pDialog && pDialog.isShowing()){
					pDialog.dismiss();
				}
			}
			// 接收到数据 传递给obj
			if (statusCode == ErrorCode.RETURN_OK) {
				System.out.println("应答内容："+response.toString());
				RespJsonData data = new RespJsonData();
					try {
						data = JsonUtil.getJson().fromJson(response.toString(), RespJsonData.class);
						int retCode  = data.getReturn_code();
						if(retCode == 800 ){	// 单独处理800错误  token已过期 重新登录
							String return_msg = data.getReturn_msg();
							Notification.toast(mContext, return_msg);
							Intent intent = new Intent();
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK  | Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.setClass(mContext, LoginActivity.class);
							mContext.startActivity(intent);
						}else if(retCode == 0){
							resp.responseSucess(data.getReturn_data());
						}else{
							Notification.toast(mContext, data.getReturn_msg());
							resp.responseFailure(data.getReturn_msg());
						}
					} catch (Exception e) {
						e.printStackTrace();
						System.out.println("错误信息：" + e.getMessage());
						Notification.toast(mContext,"数据异常...");
//						resp.responseFailure("数据异常...");
					}

			}
		}
		
	}
	

}
